<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="100px"
    >
      <el-form-item label="用户/商户账号" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入用户/商户账号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号码" prop="phonenumber">
        <el-input
          v-model="queryParams.phonenumber"
          placeholder="请输入手机号码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="行业" prop="industry">
        <el-input
          v-model="queryParams.industry"
          placeholder="请输入行业"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="城市" prop="industry">
        <el-cascader
          v-model="cityValue"
          :options="cityOptions"
          @change="handleChange"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <!--
    <el-row :gutter="10" class="mb8">
      <el-col :span="5">
        <el-select v-model="queryParams.type" class="m-2" placeholder="请选择用户类型" size="large" @changge="handleCustomerTypeChangge">
          <el-option v-for="dict in user_info_type" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"/>
        </el-select>
      </el-col>
    </el-row> -->
    <el-row
      :gutter="10"
      class="mb8"
      style="background-color: #f5f5f5; padding: 15px; border-radius: 5px"
    >
      <el-col :span="6">
        <el-select
          v-model="queryParams.type"
          class="m-2"
          placeholder="请选择用户类型"
          size="large"
          @changge="handleCustomerTypeChangge"
        >
          <el-option
            v-for="dict in user_info_type"
            :key="dict.value"
            :label="dict.label"
            :value="parseInt(dict.value)"
          />
        </el-select>
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      :data="userInfoList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column prop="userName" label="基本信息">
        <template #default="{ row }">
          <el-tooltip placement="top">
            <span style="cursor: pointer">{{ row.userName }}</span
            ><br />
            <span>{{ row.enterprise }}</span
            ><br />
            <span>{{ row.phonenumber }}</span
            ><br />
            <span>{{ row.wx }}</span
            ><br />
            <span v-show="queryParams.type === 0">{{ row.industry }}</span
            ><br />
            <span>{{ row.point }}</span
            ><br />
            <template #content>
              <div style="display: flex; align-items: center">
                <img
                  :src="row.avatar"
                  alt="Avatar"
                  style="
                    width: 80px;
                    height: 80px;
                    border-radius: 50%;
                    margin-right: 10px;
                  "
                />
                <div>
                  <span><b>用户名:</b> {{ row.userName }}</span
                  ><br />
                  <span><b>企业:</b> {{ row.enterprise }}</span
                  ><br />
                  <span><b>电话号码:</b> {{ row.phonenumber }}</span
                  ><br />
                  <span><b>微信:</b> {{ row.wx }}</span
                  ><br />
                  <span v-show="queryParams.type === 0"
                    ><b>行业:</b> {{ row.industry }}</span
                  ><br />
                  <span><b>积分:</b> {{ row.point }}</span>
                </div>
              </div>
            </template>
          </el-tooltip>
        </template>
      </el-table-column>

      <el-table-column label="常驻城市" align="center" prop="city" />
      <el-table-column
        label="行业"
        align="center"
        prop="industry"
        v-show="queryParams.type == 1"
      />
      <el-table-column label="电子邮箱" align="center" prop="email" />
      <el-table-column label="人脉数量" align="center" prop="point" />
      <el-table-column label="信用" align="center" prop="credit" />
      <el-table-column label="家乡" align="center" prop="home" />
      <el-table-column label="业务或专长" align="center" prop="business" />
      <el-table-column label="发布的动态" align="center" prop="trendsNum">
        <template #default="scope">
          <router-link :to="'/trends/' + scope.row.userId" class="link-type">
            <span>{{ scope.row.trendsNum }}</span>
          </router-link>
        </template>
      </el-table-column>
      <el-table-column
        label="创圈数量"
        align="center"
        prop="createNum"
        v-if="queryParams.type == 1"
      />
      <el-table-column label="入圈数量" align="center" prop="circleNum">
        <template #default="scope">
          <router-link :to="'/circle/' + scope.row.userId" class="link-type">
            <span>{{ scope.row.circleNum }}</span>
          </router-link>
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <router-link :to="'/merchant/' + scope.row.userId" class="link-type">
            商户列表
          </router-link>
          <el-button
            link
            type="primary"
            icon="edit"
            @click="handleDelete(scope.row, 1)"
            v-hasPermi="['main:trends:remove']"
            >拉黑</el-button
          >
          <!-- <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['main:trends:edit']">审核</el-button> -->
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row, 2)"
            v-hasPermi="['main:trends:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script setup name="UserInfo">
import { listUserInfo, delUserInfo } from "@/api/main/userInfo";
import { cityList } from "@/api/main/circle";

const { proxy } = getCurrentInstance();
const { user_info_type } = proxy.useDict("user_info_type");

const userInfoList = ref([]);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userName: null,
    phonenumber: null,
    industry: null,
    type: 0,
    city: null,
  },
});

const cityValue = ref();

const cityOptions = ref([]);

const getCityData = async () => {
  const response = await cityList();
  if (response && response.code == 200) {
    console.log(response);
    cityOptions.value = transformCityData(response.rows);
    console.log(transformCityData(response.rows));
  }
};
getCityData();

function transformCityData(cityData) {
  const result = [];
  const provinceMap = new Map();
  cityData.forEach((item) => {
    const parts = item.name.split(",");
    // 去除 "中国" 字段
    const [, province, city, district] = parts;
    if (!provinceMap.has(province)) {
      provinceMap.set(province, {
        label: province,
        value: item.id, // 存储省份的 id 到 value 字段
        children: [],
      });
    }
    const provinceObj = provinceMap.get(province);
    let cityObj = provinceObj.children.find((child) => child.label === city);
    // if (!cityObj) {
    //   cityObj = {
    //     label: city,
    //     value: item.id, // 存储城市的 id 到 value 字段
    //     children: [],
    //   };
    //   provinceObj.children.push(cityObj);
    // }
    // if (district) {
    //   cityObj.children.push({
    //     label: district,
    //     value: item.id, // 存储区县的 id 到 value 字段
    //   });
    // }
  });
  // 过滤掉 label 为空的对象
  const filteredResult = result.filter(
    (item) => item.label && item.label.trim() !== ""
  );
  return Array.from(provinceMap.values()).map((item) => {
    item.children = item.children.filter(
      (child) => child.label && child.label.trim() !== ""
    );
    return item;
  });
}

const { queryParams } = toRefs(data);
const cityName = ref();
const towCityName = ref();
// const threeCityName = ref();
const handleChange = (parms, e) => {
  // data.queryParams.cityValue = parms.join(",");
  // queryParams.value.city = parms.join(",");
  cityOptions.value.map((items) => {
    if (items.value == cityValue.value[0]) {
      cityName.value = items.label;
      if (items.children?.length > 0) {
        items.children.map((j) => {
          if (j.value == cityValue.value[1]) {
            if (j.children?.length > 0) {
              towCityName.value = j.label;
              j.children.map((k) => {
                if (k.value == cityValue.value[2]) {
                  threeCityName.value = k.label;
                }
              });
            }
          }
        });
      }
    }
  });
  data.queryParams.city = [
    cityName.value,
    towCityName.value,
    // threeCityName.value,
  ].join("-");
};

/** 查询用户/商户信息列表 */
function getList() {
  loading.value = true;
  listUserInfo(queryParams.value).then((response) => {
    userInfoList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 用户类型改变事件 */
function handleCustomerTypeChangge() {
  queryParams.value.pageNum = 1;
  queryParams.value.pageSize = 10;
  handleQuery();
}

/** 删除按钮操作 */
function handleDelete(row, index) {
  proxy.$modal
    .confirm(
      index == 1
        ? '是否确认拉黑用户"' + row.nickName + '"的数据项？'
        : '是否确认删除用户"' + row.nickName + '"的数据项？'
    )
    .then(function () {
      return delUserInfo(row.userId);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess(index == 1 ? "拉黑成功" : "删除成功");
    })
    .catch(() => {});
}

getList();

/** 重置按钮操作 */
function resetQuery() {
  data.queryParams.city = "";
  cityValue.value = "";
  proxy.resetForm("queryRef");
  handleQuery();
}
</script>
